package com.aisino.utils;


import java.net.InetAddress;
import java.security.SecureRandom;
import java.util.Random;

/**
 * 标题：
 * 
 * 描述：主键生成机制UUID
 * 
 */
public class IdGeneratorUUID {
	public IdGeneratorUUID() {
		init();
	}

	// secure random to provide non-repeating seed
	private static SecureRandom seeder;

	// cached value for mid part of string
	private static String midValue;

	private static IdGeneratorUUID key;

	static {
		key = new IdGeneratorUUID();
	}

	@SuppressWarnings("static-access")
	private void init() {
		try {
			// get the internet address
			InetAddress inet = InetAddress.getLocalHost(); // 得到地址对象
			byte[] bytes = inet.getAddress(); // 得到地址字节数组
			String hexInetAddress = hexFormat(getInt(bytes), 8);
			String thisHashCode = hexFormat(System.identityHashCode(this), 8);
			this.midValue = hexInetAddress + thisHashCode;
			seeder = new SecureRandom();
			@SuppressWarnings("unused")
			int node = seeder.nextInt();
		} catch (Exception e) {
		}
	}

	private String hexFormat(int i, int j) {
		String s = Integer.toHexString(i);
		return padHex(s, j) + s;
	}

	private String padHex(String s, int i) {
		StringBuffer stringbuffer = new StringBuffer();
		if (s.length() < i) {
			for (int j = 0; j < i - s.length(); j++) {
				stringbuffer.append("0");
			}
		}
		return stringbuffer.toString();
	}

	private int getInt(byte abyte0[]) {
		int i = 0;
		int j = 24;
		for (int k = 0; j >= 0; k++) {
			int l = abyte0[k] & 0xff;
			i += l << j;
			j -= 8;
		}
		return i;
	}

	/**
	 * 生成与主机ip有关的32位随机主健。
	 * 
	 * @return String
	 */
	public static String getUUID() {
		String sRet = null;
		try {
			long timeNow = System.currentTimeMillis();
			int timeLow = (int) timeNow & 0xFFFFFFFF;
			// get next random value
			int node = seeder.nextInt();
			sRet = (key.hexFormat(timeLow, 8) + midValue + key.hexFormat(node,
					8));
		} catch (Exception e) {
		}
		return sRet;
	}
	
	
	public static String getFixLenthString() {  
		int strLength=9;
		   Random rm = new Random();  
		      
		    // 获得随机数  
		    int pross = (int) ((1 + rm.nextInt()) * Math.pow(10, strLength));  
		  
		    // 将获得的获得随机数转化为字符串  
		    String fixLenthString = String.valueOf(pross);  
		  
		    // 返回固定的长度的随机数  
		    return fixLenthString.substring(1, strLength + 1);  
	} 
	public static String getLenthString(int strLength) {  
		   Random rm = new Random();  
		      
		    // 获得随机数  
		    int pross = (int) ((1 + rm.nextInt()) * Math.pow(10, strLength));  
		  
		    // 将获得的获得随机数转化为字符串  
		    String fixLenthString = String.valueOf(pross);  
		  
		    // 返回固定的长度的随机数  
		    return fixLenthString.substring(1, strLength + 1);  
	}  

}
